package com.carpedil.sm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.carpedil.sm.po.User;
import com.carpedil.sm.service.UserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** @author Administrator */
@WebServlet(name = "UserServlet", urlPatterns = "/user")
public class UserServlet extends HttpServlet {
  private UserService userService;

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=utf-8");
    IPage<User> users = userService.getUsersByPageParam(1, 5, 1);
    request.setAttribute("users", users.getRecords());
    request.getRequestDispatcher("/index.jsp").forward(request, response);
  }

  @Override
  public void init() throws ServletException {
    ServletContext servletContext = this.getServletContext();
    WebApplicationContext context =
        WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    userService = context.getBean("userService", UserService.class);
  }
}
